<template>
  <div class="author-works-wrapper">
    <div class="author-works-title">
      <item-list
        :items="categoriesZh"
        :idx="categoryIdx"
        @changeIdx="changeCategory"
        class="category-list"
      ></item-list>
      <search-bar
        class="author-works-search"
        v-model:searchValue="searchValue"
      ></search-bar>
    </div>

    <source-list
      class="source-list"
      :sources="filteredSources"
      @fetchSourceAbstracts="fetchSourceAbstracts"
    ></source-list>
  </div>
</template>

<script lang="ts" setup>
import SearchBar from '@/components/utils/SearchBar.vue'
import SourceList from '@/components/SourceList.vue'
import ItemList from '@/components/utils/ItemList.vue'
import { ref, reactive, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { post } from '@/utils/request'
import { parseInt } from 'lodash'

const categories = ['works']
const categoriesZh = ['作品']
const searching = ref(false)
const searchValue = ref('')

const works = reactive([] as App.Source[])
let worksPage = 0

let categoryIdx = computed(() => {
  return categories.includes(route.query.q as string)
    ? categories.indexOf(route.query.q as string)
    : 0
})

const sources = works

const filteredSources = computed(() => {
  return sources.filter((source) => {
    return (
      source.title.includes(searchValue.value) ||
      source.digest.includes(searchValue.value)
    )
  })
})

const router = useRouter(),
  route = useRoute()
function changeCategory(idx: number) {
  router.push({
    path: route.path,
    query: {
      q: categories[idx],
    },
  })
}

function fetchSourceAbstracts() {
  switch (categoryIdx.value) {
    case 0:
      fetchWorksSourceAbstracts()
      break
  }
}

function fetchWorksSourceAbstracts() {
  post('author/source', {
    id: parseInt(route.params.id as string),
    page: ++worksPage,
    sort: 2,
  })
    .then((res) => {
      ;(res.data as any).forEach((item: any) => works.push(item))
    })
    .catch((error) => {
      worksPage--
    })
}
</script>

<style scoped lang="scss">
$w: var(--innerWidthPart1);
$th: calc(var(--innerWidthPart1) * 0.065);

.author-works-wrapper {
  width: $w;

  .author-works-title {
    position: relative;
    box-sizing: border-box;
    width: $w;
    height: $th;
    padding: 0 calc($w / 50);
    border-bottom: 1px solid var(--gray);

    .category-list {
      float: left;
      --itemListWidth: calc($w * 0.6);
      --itemListHeight: calc($th);
      --itemNum: 5;
    }

    .author-works-search {
      float: right;
      --searchBarWidth: calc($w * 0.2);
      --searchBarHeight: $th;
      --searchBarFontSize: calc($th / 4);
      --searchBarInnerHeight: calc($th * 0.6);
      --backgroundColor: white;

      &:focus-within {
        --searchBarWidth: calc($w * 0.35);
      }
    }
  }

  .source-list {
    --sourceListWidth: $w;
  }
}
</style>
